#include <iostream>
#include "log.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstdlib>
#include <strings.h>
#include <string>
#include <cstring>
#include <functional>
#include <unordered_map>

Log lg;

// using func_t = std::function<std::string(const std::string &)>;
// using func_t = std::function<std::string(const std::string &)>;

typedef std::function<std::string(const std::string &)> func_t;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};

const uint16_t defaultport = 8080;
const string defaultip = "0.0.0.0";

class udpServer
{
public:
    udpServer(const uint16_t &port = defaultport, const string &ip = defaultip)
        : port_(port), ip_(ip), sockfd_(0)
    {
    }

    void Init()
    {
        // 1.创建套接字文件描述符
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd_ == -1)
        {
            lg(Fatal, "socket creat fail, sockfd:%d", sockfd_);
            exit(SOCKET_ERR);
        }
        lg(Info, "socket creat success, sockfd:%d", sockfd_);

        // 2.bind端口号和ip
        struct sockaddr_in sk;
        bzero(&sk, sizeof(sk)); // 初始化0
        sk.sin_family = AF_INET;
        sk.sin_port = htons(port_);
        sk.sin_addr.s_addr = inet_addr(ip_.c_str()); // 由于ip地址设置为0所以不需要转换为网络序列

        socklen_t len = sizeof(sk);
        if (bind(sockfd_, (struct sockaddr *)&sk, len) < 0)
        {
            lg(Fatal, "bind fail, errno:%d, err string:%s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success, errno:%d, err string:%s", errno, strerror(errno));
    }

    void is_user(const struct sockaddr_in &client,const uint16_t &clientport,const std::string &clientip)
    {
        auto iter=users.find(clientip);
        if(iter==users.end())
        {
            users.insert({clientip,client});
            std::cout << "[" << clientip << ":" << clientport << "] add to online user." << std::endl;
        }
    }

    void Broadcast(std::string &info,const uint16_t &clientport,const std::string &clientip)
    {
        for(auto &e:users)
        {
            string ret;
            ret+="[";
            ret+=clientip;
            ret+=" : ";
            ret+=to_string(clientport);
            ret+="] ";
            ret+=info;

            // 发送数据给客户端
            sendto(sockfd_, ret.c_str(), ret.size(), 0, (struct sockaddr *)&e.second, sizeof(e.second));
        }

    }

    void Run()
    {
        isrunning_ = true;

        while (isrunning_)
        {

            // 接收客户端的消息
            char buffer[1024];
            memset(buffer, 0, sizeof(buffer));
            struct sockaddr_in client;
            bzero(&client, sizeof(client));
            socklen_t len = sizeof(client);
            int n = recvfrom(sockfd_, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                lg(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }

            uint16_t clientport=ntohs(client.sin_port);
            std::string clientip=inet_ntoa(client.sin_addr);

            //判断用户是否在哈希表中
            is_user(client,clientport,clientip);

            buffer[n] = 0;
            //cout << "server get massge:" << buffer << endl;

            string info=buffer;
            //转发给users表中的用户
            Broadcast(info,clientport,clientip);
        }
    }

    ~udpServer()
    {
        close(sockfd_);
    }

private:
    int sockfd_; // 套接字描述符
    uint16_t port_;
    std::string ip_;

    bool isrunning_;
    std::unordered_map<std::string,struct sockaddr_in> users;   //ip确定唯一性
};